package com.exercise.widgets.recyclerview.selection.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.selection.ItemDetailsLookup
import androidx.recyclerview.selection.SelectionTracker
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.exercise.widgets.databinding.ItemContactListBinding
import com.exercise.widgets.recyclerview.selection.entity.Contact

class ContactAdapter(
    private val data: MutableList<Contact> = mutableListOf(),
    private val onClickEdit: (View, Int) -> Unit
) : Adapter<ContactAdapter.ContactViewHolder>() {
    var tracker: SelectionTracker<Contact>? = null

    fun getItem(position: Int): Contact {
        return data[position]
    }

    fun indexOf(item: Contact): Int {
        return data.indexOf(item)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactViewHolder {
        val binding =
            ItemContactListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ContactViewHolder(binding, onClickEdit) {
            data[it]
        }
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun onBindViewHolder(holder: ContactViewHolder, position: Int) {
        val item = data[position]
        tracker?.let {
            holder.bindData(data[position], it.isSelected(item))
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun setList(contacts: List<Contact>) {
        this.data.run {
            clear()
            addAll(contacts)
            notifyDataSetChanged()
        }
    }

    class ContactViewHolder(
        val binding: ItemContactListBinding,
        val onClickEdit: (View, Int) -> Unit,
        val takeSelectionKey: (Int) -> Contact
    ) : ViewHolder(binding.root) {
        init {
            binding.editBtn.setOnClickListener {
                onClickEdit(it,layoutPosition)
            }
        }

        fun bindData(contact: Contact, isActivated: Boolean) {
            binding.tvName.text = contact.name
            binding.tvTelephone.text = contact.telephone
            binding.root.isActivated = isActivated
        }

        fun getItemDetail() = object : ItemDetailsLookup.ItemDetails<Contact>() {
            override fun getPosition(): Int {
                return layoutPosition
            }

            override fun getSelectionKey(): Contact {
                return takeSelectionKey(layoutPosition)
            }
        }

    }

}